package com.songsong.myblog2.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.songsong.myblog2.domain.Photo;
import com.songsong.myblog2.domain.UserImage;
import com.songsong.myblog2.service.UserService;
import com.songsong.myblog2.util.FileUtil;
import com.songsong.myblog2.util.TimeUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class uploadFileController {
    /*注入userService*/
    @Autowired
    private UserService userService;

    /**
     * 文章编辑本地上传图片
     */
    @RequestMapping("/uploadImage")
    public @ResponseBody
    Map<String, Object> uploadImage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "editormd-image-file", required = false) MultipartFile file) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            request.setCharacterEncoding("utf-8");
            //设置返回头后页面才能获取返回url
            response.setHeader("X-Frame-Options", "SAMEORIGIN");

            FileUtil fileUtil = new FileUtil();
            String filePath = this.getClass().getResource("/").getPath().substring(1) + "blogImg/";
            String fileContentType = file.getContentType();
            String fileExtension = fileContentType.substring(fileContentType.indexOf("/") + 1);
            TimeUtil timeUtil = new TimeUtil();
            String fileName = timeUtil.getLongTime() + "." + fileExtension;

            String subCatalog = "blogArticles/" + new TimeUtil().getFormatDateForThree();
            String fileUrl = fileUtil.uploadFile(fileUtil.multipartFileToFile(file, filePath, fileName), subCatalog);

            resultMap.put("success", 1);
            resultMap.put("message", "上传成功");
            resultMap.put("url", fileUrl);
        } catch (Exception e) {
            try {
                response.getWriter().write("{\"success\":0}");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return resultMap;
    }

    /**
     * 上传头像
     */
    @PostMapping("/uploadHead")
    @ResponseBody
    public JSONObject uploadHead(HttpServletRequest request) {
        //获取用户手机号
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        JSONObject jsonObject = new JSONObject();
        String img = request.getParameter("img");
        //获得上传文件的后缀名
        int index = img.indexOf(";base64,");
        String strFileExtendName = "." + img.substring(11, index);
        img = img.substring(index + 8);
        String subCatalog = "userPhoto/" + username;
        try {
            FileUtil fileUtil = new FileUtil();
            String filePath = this.getClass().getResource("/").getPath().substring(1) + "userImg/";
            TimeUtil timeUtil = new TimeUtil();
            File file = fileUtil.base64ToFile(filePath, img, timeUtil.getLongLongTime() + strFileExtendName);
            String url = fileUtil.uploadFile(file, subCatalog);
            jsonObject.put("status", "200");
            jsonObject.put("avatarImgUrl", url);
            Photo photo = new Photo();
            photo.setUserurl(url);
            photo.setUserdate(timeUtil.getFormatDateForThree());
            photo.setUserphone(username);
            //将信息保存到数据库中
            userService.updateUserHead(photo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonObject;
        }
        return jsonObject;
    }

    /*用户相册多文件上传*/
    @RequestMapping("/uploadUserPhoto")
    @ResponseBody
    public JSONArray uploadUserPhoto(MultipartFile[] file) {
        /*获取用户手机号*/
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        /*获取后缀名*/
        String fileName = file[0].getOriginalFilename();
        int i = fileName.indexOf(".");
        String fileExtension = fileName.substring(i, fileName.length());
        FileUtil fileUtil = new FileUtil();
        String filePath = this.getClass().getResource("/").getPath().substring(1) + "userImg/";
        TimeUtil timeUtil = new TimeUtil();
        fileName = timeUtil.getLongLongTime() + fileExtension;
        String subCatalog = "userPhoto/" + username;
        String fileUrl = fileUtil.uploadFile(fileUtil.multipartFileToFile(file[0], filePath, fileName), subCatalog);
        /*拿到了存到oss中的路径之后  在将该路径 和用户手机号存到数据库中*/
        /*调用方法保存到数据库中*/
        UserImage userImage = new UserImage();
        userImage.setImageUrl(fileUrl);//设置url
        userImage.setImageDate(timeUtil.getFormatDateForThree());//设置上传时间
        userImage.setUsername(username);//设置用户手机号
        userImage.setImageId(timeUtil.getLongLongTime());
        userService.addUserIamge(userImage);
        JSONArray jsonArray = new JSONArray();
        Map<String, Object> res = new HashMap<>();
        res.put("code", "0");
        res.put("msg", "上传成功");
        res.put("data", userImage);
        jsonArray.add(res);
        return jsonArray;
    }
}
